#!/bin/bash
# chkconfig: 2345 55 25
# description: bt Cloud Service

### BEGIN INIT INFO
# Provides:          bt
# Required-Start:    $all
# Required-Stop:     $all
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: starts bt
# Description:       starts the bt
### END INIT INFO

if [ "$(id -u)" -ne 0 ]; then
    echo "===================警告======================"
    echo "检测到非root用户权限执行bt命令，可能存在异常 "
    echo "请使用此命令重新执行：sudo wg"
    echo "============================================="
    exit ;
fi

panel_init(){
        panel_path=/www/endpoint
        pidfile=/var/run/logs/appWatchdog.pid
        chmod 700 $panel_path/appWatchdog &> /dev/null
        log_file=$panel_path/logs
}
panel_init

get_panel_pids(){
        isStart=$(ps aux|grep -E '(/www/endpoint/appWatchdog)'|grep -v grep|awk '{print $2}'|xargs)
        pids=$isStart
        arr=$isStart
}

get_task_pids(){
        isStart=$(ps aux|grep -E '(VideoLocalEndpoint)'|grep -v grep|awk '{print $2}'|xargs)
        pids=$isStart
        arr=$isStart
}

panel_start()
{
        isStart=`ps aux|grep 'runserver:app'|grep -v grep|awk '{print $2}'`
        if [ "$isStart" != '' ];then
                kill -9 $isStart
        fi
        get_panel_pids

        
        if [ "$isStart" == '' ];then
                rm -f $pidfile &> /dev/null

                echo -e "Starting Bt-Panel...\c"
                echo '\n' >> $log_file/error.log
                if [ $? -ne 0 ];then
                    $panel_path/appWatchdog >> $log_file/start.log 2>&1 &
                else
                    $panel_path/appWatchdog >> $log_file/error.log 2>&1 &
                fi
                isStart=""
                n=0
                while [[ "$isStart" == "" ]];
                do
                        echo -e ".\c"
                        sleep 0.5
                        get_panel_pids
                        let n+=1
                        if [ $n -gt 8 ];then
                                break;
                        fi
                done
                if [ "$isStart" == '' ];then
                        echo -e "\033[31mfailed\033[0m"
                        echo '------------------------------------------------------'
                        tail -n 20 $log_file/error.log
                        echo '------------------------------------------------------'
                        echo -e "\033[31mError: BT-Panel service startup failed.\033[0m"
                fi
                echo -e "	\033[32mdone\033[0m"
        else
                echo "Starting Bt-Panel... Bt-Panel (pid $(echo $isStart)) already running"
        fi
}


panel_stop()
{
        echo -e "Stopping Bt-Tasks...\c";
        get_task_pids
        arr=($pids)
        for p in ${arr[@]}
        do
                kill -9 $p
        done
        echo -e "	\033[32mdone\033[0m"

        echo -e "Stopping Bt-Panel...\c";

        get_panel_pids
        for p in ${arr[@]}
        do
                kill -9 $p &>/dev/null
        done

        if [ -f $pidfile ];then
                rm -f $pidfile &> /dev/null
        fi
        echo -e "	\033[32mdone\033[0m"
}

panel_status()
{
        get_panel_pids
        if [ "$isStart" != '' ];then
                echo -e "\033[32mBt-Panel (pid $(echo $isStart)) already running\033[0m"
        else
                echo -e "\033[31mBt-Panel not running\033[0m"
        fi

        get_task_pids
        if [ "$isStart" != '' ];then
                echo -e "\033[32mBt-Task (pid $isStart) already running\033[0m"
        else
                echo -e "\033[31mBt-Task not running\033[0m"
        fi
}

panel_reload()
{
	isStart=$(ps aux|grep 'runserver:app'|grep -v grep|awk '{print $2}')
        if [ "$isStart" != '' ];then
		kill -9 $isStart
		sleep 0.5
	fi
	get_panel_pids
        if [ "$isStart" != '' ];then

	    get_panel_pids
	for p in ${arr[@]}
        do
                kill -9 $p
        done
		rm -f $pidfile
		echo -e "Reload Bt-Panel.\c";
                nohup $panel_path/appWatchdog >> $log_file/error.log 2>&1 &
		isStart=""
		n=0
		while [[ "$isStart" == "" ]];
		do
			echo -e ".\c"
			sleep 0.5
			get_panel_pids
			let n+=1
			if [ $n -gt 8 ];then
				break;
			fi
		done
        if [ "$isStart" == '' ];then
                panel_port_check
                echo -e "\033[31mfailed\033[0m"
                echo '------------------------------------------------------'
                tail -n 20 $log_file/error.log
                echo '------------------------------------------------------'
                echo -e "\033[31mError: BT-Panel service startup failed.\033[0m"
                return;
        fi
        echo -e "	\033[32mdone\033[0m"
    else
        echo -e "\033[31mBt-Panel not running\033[0m"
        panel_start
    fi
}

error_logs()
{
	tail -n 100 $log_file/error.log
}


case "$1" in
        'start')
                panel_start
                ;;
        'stop')
                panel_stop
                ;;
        'restart')
                panel_stop
		sleep 1
                panel_start
                ;;
        'reload')
                panel_reload
                ;;
        'status')
                panel_status
                ;;
        'logs')
        		error_logs
        		;;
        'default')
                echo -e "=================================================================="
                echo -e "\033[32mBT-Panel default info!\033[0m"
                echo -e "=================================================================="
                echo -e "\033[33m注意：初始密码仅在首次登录面板前能正确获取，其它时间请通过 bt 5 命令修改密码\033[0m"
                echo -e "=================================================================="
                ;;
        *)
                if [ "${LANG}" != "en_US.UTF-8" ];then
                    export LANG=en_US.UTF-8 &> /dev/null
                fi
                if [ "${LC_ALL}" != "en_US.UTF-8" ];then
                    export LC_ALL=en_US.UTF-8 &> /dev/null
                fi
        ;;
esac

